<template>
    <div>
        <nav-header title="发布"></nav-header>
        <!-- 标题 -->
        <div class="container">
            <!-- 通过 pattern 进行正则校验 -->
            <!-- 标题 -->
            <van-field style="margin-top: 10px" v-model="title" name="pattern" placeholder="请输入标题" />

            <!-- 选择分类 -->
            <van-field readonly clickable name="picker" :value="value" placeholder="请选择" @click="showPicker = true" />
            <van-popup v-model="showPicker" position="bottom">
                分类：
                <van-picker show-toolbar :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
            </van-popup>

            <!-- 文章描述 -->
            <van-field style="margin-top: 10px" v-model="content" rows="5" autosize type="textarea" placeholder="描述" />

            <!-- 选择图片 -->
            <van-uploader v-model="fileList" :max-count="3" :after-read="uploadImg" />
            <!-- 确认提交 -->
        </div>
        <div class="btn" @click="fabu()">发布</div>
    </div>
</template>

<script>
import NavHeader from "../../components/Nav-Header.vue";
import { Popup } from "vant";
import { Uploader } from "vant";
import { Picker } from "vant";
export default {
    name: "App03Publish",
    components: {
        NavHeader,
        [Popup.name]: Popup,
        [Uploader.name]: Uploader,
        [Picker.name]: Picker,
    },
    data() {
        return {
            title: "",
            content: "",
            fileList: [],
            img: [],
            value: "",
            columns: [],
            list: [],
            list_id: '',
            showPicker: false,
            userInfo: []
        };
    },
    mounted() {
        this.getList()
        let userInfos = JSON.parse(localStorage.getItem('xl-userInfo'))
        this.userInfo = userInfos
        // console.log(this.userInfo)
    },
    methods: {
        getList() {
            this.$axios('/api/get_cate_list')
                .then(res => {
                    console.log(res)
                    if (res.code == 0) {
                        this.list = res.data
                        for (let i = 0; i < res.data.length; i++) {
                            this.columns.push(res.data[i].name)

                        }
                    }
                })
        },
        onConfirm(value) {
            this.value = value;
            this.showPicker = false;
        },
        async uploadImg(e) {
            let file = e.file;
            // console.log(file);
            //   1. 需要获取到一个上传前的凭证
            let { token } = await this.getUploadToken();
            // console.log('token'+ token);
            let exname = file.name.slice(file.name.lastIndexOf("."));
            // console.log('exname'+ exname)
            let key = `${new Date().getTime()}_${Math.random().toString(36).slice(2)}${exname}`;
            // console.log('key'+ key)
            //  2.  三个参数一起发给七牛云的服务器  token   file  文件名
            // 想上传文件  FormData
            let formData = new FormData();
            formData.append("key", key);
            formData.append("token", token);
            formData.append("file", file);

            this.$axios.post("https://upload-z1.qiniup.com", formData).then((res) => {
                // console.log(res);
                let imageSrc = `http://toutiao.longxiaokj.com/${res.key}`;
                // console.log(imageSrc)
                this.img.push(imageSrc)
                console.log(this.img)
                //  给对象动态的添加属性 并不会触发自动更新
                this.$forceUpdate();
            });


        },
        //  获取上传前的凭证
        getUploadToken() {
            return this.$axios.get(
                "https://d33a5037-6c63-4e92-8bb1-30018ab701ea.bspapp.com/http/upload/token"
            );
        },
        fabu() {
            let index = this.columns.findIndex(index => index == this.value)
            this.list_id = this.list[index]._id
            console.log(this.list_id)
            // let images = this.img.toString()
            //  console.log(images)
            this.$axios.post('/api/add_article', {
                title: this.title,
                content: this.content,
                cate_name: this.value,
                cate_id: this.list_id,
                author: this.userInfo.nickname,
                author_id: this.userInfo._id,
                imageSrc: this.img
            }).then((res) => {
                console.log(res)
                if (res.code == 0) {
                    this.$toast('发布成功！')
                    this.$router.push('/home')
                } else {
                    this.$toast(res.msg)
                }
            })
        }
    },
};
</script>

<style lang="scss" scoped>
.btn {
    width: 80%;
    height: 40px;
    color: white;
    background-color: #07c160;
    margin: 50px auto;
    text-align: center;
    line-height: 40px;
    border-radius: 16px;
}
</style>
